package com.ebelter.scalenomaldemo;

import android.bluetooth.BluetoothDevice;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;

import com.ebelter.scaleblesdk.ScaleBleManager;
import com.ebelter.scaleblesdk.ble.bluetooth.OnDeviceBindFoundListener;
import com.ebelter.scaleblesdk.ble.bluetooth.callback.ConnectCallback;
import com.ebelter.scaleblesdk.ble.bluetooth.callback.FirmwareUpgradeCallback;
import com.ebelter.scaleblesdk.ble.bluetooth.callback.ScanResultCallback;
import com.ebelter.scaleblesdk.ble.bluetooth.impl.IFirmwareUpgradeCallback;
import com.ebelter.scaleblesdk.ble.bluetooth.impl.IMeasureResultCallback;
import com.ebelter.scaleblesdk.ble.bluetooth.impl.IUserInfoChangedCallback;
import com.ebelter.scaleblesdk.common.BleFild;
import com.ebelter.scaleblesdk.common.Fields;
import com.ebelter.scaleblesdk.common.FileNames;
import com.ebelter.scaleblesdk.helper.SharePrefrenceHelper;
import com.ebelter.scaleblesdk.model.MeasureResult;
import com.ebelter.scaleblesdk.model.OfflineMeasureResult;
import com.ebelter.scaleblesdk.model.Scale;
import com.ebelter.scaleblesdk.model.ScaleUser;
import com.ebelter.scaleblesdk.model.Weight;
import com.ebelter.scaleblesdk.ble.upgrade.FirmwareUpgrader;
import com.ebelter.scaleblesdk.util.SystemTool;
import com.ebelter.scaleblesdk.util.ULog;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private TextView tvSearchResult;
    private TextView tvBindStatus;
    private TextView tvReceiveData;
    private TextView tvOfflineData;
    private TextView tvFirmwareVersion;
    private TextView tvPercentFirmwareUpgrade;
    private ScaleBleManager sbm;
    private BluetoothDevice curDevice;
    private boolean isDeviceBound;
    private final static String TAG = "MainActivity";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        //初始化蓝牙模块
        ScaleBleManager.init(this);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        tvSearchResult = (TextView) findViewById(R.id.tv_search_result);
        tvBindStatus = (TextView) findViewById(R.id.tv_bind_status);
        tvReceiveData = (TextView) findViewById(R.id.tv_receive_data);
        tvOfflineData = (TextView) findViewById(R.id.tv_receive_offline_data);
        tvFirmwareVersion = (TextView) findViewById(R.id.tv_firmware_version);
        tvPercentFirmwareUpgrade = (TextView) findViewById(R.id.tv_percent_firmware_upgrade);

        findViewById(R.id.btn_bind).setOnClickListener(this);
        findViewById(R.id.btn_unbind).setOnClickListener(this);
        findViewById(R.id.btn_receive_offline).setOnClickListener(this);
        findViewById(R.id.btn_clear_user).setOnClickListener(this);
        findViewById(R.id.btn_firmware_version).setOnClickListener(this);
        findViewById(R.id.btn_ble_firmware_update).setOnClickListener(this);
        findViewById(R.id.btn_scale_firmware_update).setOnClickListener(this);


        initData();

    }

    private void initData() {
        sbm = ScaleBleManager.getInstance();

        //注册连接监听器
        sbm.registerConnectCallback(mConnectCallback);
        //注册秤用户信息改变监听器
        sbm.registerUserInfoChangedCallback(mUserInfoChangedCallback);
        //注册测量结果监听器
        sbm.registerMeasureResultCallback(measureResultCallback);
        //注册固件升级监听器
//        sbm.registerFirmwareUpgradeCallback(mFirmwareUpdateCallback);

        //是否已绑定体脂秤
        isDeviceBound = sbm.isDeviceBound(this);
        ULog.i(TAG, "-----initData--isDeviceBound = " + isDeviceBound);
        if (!isDeviceBound) {
            //  TODO 获取搜索设备结果，跳转到绑定设备界面，进行设备绑定

        }

    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_bind://绑定设备
                if (curDevice != null) {
                    sbm.startConnect(curDevice);
                }
                break;
            case R.id.btn_unbind://解绑
                if (curDevice != null) {
                    sbm.unbindDevice();
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            tvBindStatus.setText("当前绑定设备： ");
                        }
                    });

                }
                break;
            case R.id.btn_receive_offline:
                //请求离线测量数据,连接成功下发用户信息后，才能请求离线测量数据，
                sbm.requestOfflineData(ScaleUser.getUser().getBtId());
                break;
            case R.id.btn_clear_user://清除用户信息
                sbm.sendDelAllUser();
                break;
            case R.id.btn_firmware_version://获取固件版本
//                getFirmwareVersion();
                break;
            case R.id.btn_ble_firmware_update://蓝牙固件升级
//                sbm.requestBleFirmwareUpgrade();
                break;
            case R.id.btn_scale_firmware_update://秤固件升级
//                sbm.requestScaleFirmwareUpgrade();
                break;

        }
    }

    @Override
    protected void onDestroy() {
        if (sbm != null) {
            sbm.releaseOnActivityDestroy();
        }
        super.onDestroy();
    }


    /**
     * 下发用户信息到秤
     */
    private void sendUserInfoToScale() {
        //初始化ScaleUser信息
        ScaleUser user = ScaleUser.getUser();

        user.setNike("张三");
        user.setUid(1);
        String btId = user.toBtId("00001");
        ULog.i(TAG, "-----sendUserInfoToScale--btId = " + btId);
        user.setBtId(btId);
        user.setAge(28);
        user.setSex(0);
        user.setWeight(60.0f);
        user.setImpedance(244.0f);
        user.setHeight(173);

        ULog.i(TAG, "-----sendUserInfoToScale----isLoginPattren = " + user.isLoginPattren());
        sbm.sendUserInfo(user);
    }





    /**
     * 连接结果回调
     */
    private ConnectCallback mConnectCallback = new ConnectCallback() {
        @Override
        public void onConnected(final BluetoothDevice device) {
            ULog.i(TAG, "------onDeviceConnected------连接成功！");
            curDevice = device;
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    tvBindStatus.setText("当前绑定设备：" + device.getName());
                }
            });
            //发用户信息到秤
            sendUserInfoToScale();
        }

        @Override
        public void onScaleWake() {
            ULog.i(TAG, "------onScaleWake------");
        }

        @Override
        public void onScaleSleep() {
            ULog.i(TAG, "------onScaleSleep------");
        }

        @Override
        public void onDisConnected() {
            ULog.i(TAG, "------onDisConnected------");
        }


    };

    /**
     * 秤用户信息改变监听回调
     */
    private IUserInfoChangedCallback mUserInfoChangedCallback = new IUserInfoChangedCallback() {
        @Override
        public void onUserInfoUpdateSuccess() {
//            ULog.i(TAG, "-----onUserInfoUpdateSuccess--SDK里经常要更新秤用户信息，最好不要打印----");
        }

        @Override
        public void onDeleteAllUsersSuccess() {
            ULog.i(TAG, "-----onDeleteAllUsersSuccess------");
        }
    };

    /**
     * 测量结果监听回调
     */
    private IMeasureResultCallback measureResultCallback = new IMeasureResultCallback() {

        @Override
        public void onReceiveMeasureResult(final MeasureResult result) {
            ULog.i(TAG, "-----onFatMeasureResult------result = " + result);
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    tvReceiveData.setText("接收到蓝牙信息：" + result);
                }
            });

        }

        @Override
        public void onWeightMeasureResult(Weight weight) {
            ULog.i(TAG, "-----onWeightMeasureResult------weight = " + weight);
        }

        @Override
        public void onWeightOverLoad() {
            ULog.i(TAG, "-----onWeightOverLoad------");
        }

        @Override
        public void onReceiveHistoryRecord(final OfflineMeasureResult result) {
            ULog.i(TAG, "-----onReceiveHistoryRecord------result = " + result);
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    tvOfflineData.setText("接收到离线信息：" + result);
                }
            });
        }

        @Override
        public void onFatMeasureError(int type) {
            ULog.i(TAG, "-----onFatMeasureError------type = " + type);
        }

        @Override
        public void onHistoryUploadDone() {
            ULog.i(TAG, "-----onHistoryUploadDone------");
        }

    };


    public void bt_scan(View view) {
        sbm = ScaleBleManager.getInstance();
        sbm.setScanTimeout(12000);//设置扫描周期 这里不设置也是默认12秒
        sbm.startScan(new ScanResultCallback() {
            @Override
            public void onDiscovered(final BluetoothDevice device) {
                curDevice = device;
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        ULog.i(TAG,"搜索到设备：" + device.getName() + "\t" + device.getAddress());
                        if (!TextUtils.isEmpty(device.getName())){
                            if ("Body Fat-B1".equals(device.getName())){//说明搜索体脂称成功 开始连接设备
                                if (sbm!=null)sbm.startConnect(device);
                            }else if (device.getName().contains("lnv_111")||device.getName().contains("lnv_112")){
                                ULog.i(TAG,"----------搜索目标设备到设备：" + device.getName() + "\t" + device.getAddress());
                                if (sbm!=null)sbm.startConnect(device);
                            }
                        }

                    }
                });
            }
        });
    }
}
